package com.ayuku.commons.business.appgroup;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ayuku.commons.AyukuDB;
import com.ayuku.commons.ConstClientServer;
import com.ayuku.commons.UtilServer;
import com.ayuku.retail.persistence.model.AppGroup;
import com.ayuku.retail.persistence.model.AppUserGroupFunc;
import com.ayuku.retail.persistence.modelmanual.VGroupFunctions;

public class AppGroupImpl {

	public static List<AppGroup> getList(String arg) throws Exception {
		List<AppGroup> lst = AyukuDB
				.getPersist()
				.readList(
						AppGroup.class,
						"SELECT * FROM app_group WHERE ucase(trim(id)) LIKE ucase(?) or ucase(trim(name)) LIKE ucase(?)",
						new Object[] { arg, arg });

		return lst;
	}

	public static Map<String, Object> getById(String key) throws IOException,
			SQLException, Exception {

		Map<String, Object> mp = new HashMap<String, Object>();
		AppGroup pj = AyukuDB.getPersist().readByPrimaryKey(AppGroup.class,
				new Object[] { key });
		mp.put(ConstClientServer.STR_HDR, pj);

		List<AppUserGroupFunc> lst = AyukuDB.getPersist().readList(
				AppUserGroupFunc.class,
				"select * from app_user_group_func where group_id=?",
				new Object[] { key });
		mp.put(ConstClientServer.STR_DTL, lst);

		return mp;
	}

	public static boolean getAllowedView(String groupId, String funcId)
			throws Exception {

		List<AppUserGroupFunc> lst = AyukuDB
				.getPersist()
				.readList(
						AppUserGroupFunc.class,
						"select * from app_user_group_func where trim(group_id) = ? and func_id = ? and access_view ='true'",
						new Object[] { groupId, funcId });

		if (lst.size() > 0) {
			return true;
		}

		return false;
	}

	public static boolean getAllowedAdd(String groupId, String funcId)
			throws Exception {

		List<AppUserGroupFunc> lst = AyukuDB
				.getPersist()
				.readList(
						AppUserGroupFunc.class,
						"select * from app_user_group_func where trim(group_id) = ? and func_id = ? and access_add='true'",
						new Object[] { groupId, funcId });

		if (lst.size() > 0) {
			return true;
		}

		return false;
	}

	public static boolean getAllowedEdit(String groupId, String funcId)
			throws Exception {

		List<AppUserGroupFunc> lst = AyukuDB
				.getPersist()
				.readList(
						AppUserGroupFunc.class,
						"select * from app_user_group_func where trim(group_id) = ? and func_id = ? and access_edit='true'",
						new Object[] { groupId, funcId });

		if (lst.size() > 0) {
			return true;
		}

		return false;
	}

	public static boolean getAllowedDelete(String groupId, String funcId)
			throws Exception {

		List<AppUserGroupFunc> lst = AyukuDB
				.getPersist()
				.readList(
						AppUserGroupFunc.class,
						"select * from app_user_group_func where trim(group_id) = ? and func_id = ? and access_delete='true'",
						new Object[] { groupId, funcId });

		if (lst.size() > 0) {
			return true;
		}

		return false;
	}

	public static AppUserGroupFunc getFunc(String groupId, String funcId)
			throws Exception {
		System.out.println("groupId: " + groupId);
		System.out.println("ufunctId: " + funcId);

		List<AppUserGroupFunc> lst = AyukuDB
				.getPersist()
				.readList(
						AppUserGroupFunc.class,
						"select * from app_user_group_func where group_id = ? and func_id = ? order by id asc",
						new Object[] { groupId, funcId });

		AppUserGroupFunc func = null;

		if (lst != null && lst.size() > 0) {
			func = lst.get(lst.size() - 1);
			System.out.println("View: " + func.getAccessView());
			System.out.println("Add: " + func.getAccessAdd());
			System.out.println("Edit: " + func.getAccessEdit());
			System.out.println("Delete: " + func.getAccessDelete());
		}

		return func;
	}

	public static int delete(List<String> ids) throws Exception {
		int n = 0;
		try {
			AyukuDB.getPersist().setAutoCommit(false);
			for (int j = 0; j < ids.size(); j++) {
				String key = ids.get(j);
				n += delete(key);
			}
			AyukuDB.getPersist().commit();
		} catch (Exception e) {
			e.printStackTrace();
			AyukuDB.getPersist().rollback();			
			throw new Exception();
		} finally {
			AyukuDB.getPersist().setAutoCommit(true);
		}
		return n;
	}

	public static int delete(String key) throws Exception {

		if ("administrator".equals(key)) {
			return 1;
		}

		int n = AyukuDB.getPersist().executeUpdate(
				"delete from app_group where id = ?", new Object[] { key });

		// DELETE ALL DETAIL
		AyukuDB.getPersist().executeUpdate(
				"delete from app_user_group_func where group_id = ?",
				new Object[] { key });

		return n;
	}

	@SuppressWarnings("unchecked")
	public static int add(Map<String, Object> mp) throws Exception {
		// INSERT HEADER
		AyukuDB.getPersist().setAutoCommit(false);

		AppGroup appGrp = (AppGroup) mp.get(ConstClientServer.STR_HDR);

		setModifiedDate(appGrp);

		int n = AyukuDB.getPersist().insert(appGrp);
		// end

		List<AppGroup> lappGrp = AyukuDB
				.getPersist()
				.readList(
						AppGroup.class,
						"SELECT * FROM app_group WHERE ucase(trim(name))=? order by id asc",
						new Object[] { appGrp.getName() + "" });

		if (lappGrp != null && lappGrp.size() > 0) {
			appGrp = (AppGroup) lappGrp.get(lappGrp.size() - 1);
		}

		// DELETE ALL DETAIL
		AyukuDB.getPersist().executeUpdate(
				"delete from app_user_group_func where trim(group_id) = ?",
				new Object[] { appGrp.getId() });
		// end

		// INSERT DETAIL
		int ndtl = 0;
		List<VGroupFunctions> lst = (List<VGroupFunctions>) mp
				.get(ConstClientServer.STR_DTL);

		for (int j = 0; j < lst.size(); j++) {
			VGroupFunctions fnc = (VGroupFunctions) lst.get(j);
			System.out.println("Id: " + fnc.getId());
			System.out.println("Name: " + fnc.getName());
			System.out.println("View: " + fnc.getView());
			System.out.println("Add: " + fnc.getAdd());
			System.out.println("Edit: " + fnc.getEdit());
			System.out.println("Delete: " + fnc.getDelete());

			AppUserGroupFunc groupfunc = new AppUserGroupFunc();
			groupfunc.setGroupId(appGrp.getId());
			groupfunc.setFuncId(fnc.getId());
			groupfunc.setAccessView(fnc.getView());
			groupfunc.setAccessAdd(fnc.getAdd());
			groupfunc.setAccessEdit(fnc.getEdit());
			groupfunc.setAccessDelete(fnc.getDelete());

			// setModifiedDAte
			setDtlDateuser(groupfunc, appGrp);
			// end of

			ndtl += AyukuDB.getPersist().insert(groupfunc);
		}

		AyukuDB.getPersist().commit();
		AyukuDB.getPersist().setAutoCommit(true);
		return n;
	}

	@SuppressWarnings("unchecked")
	public static int update(Map<String, Object> mp) throws Exception {
		AyukuDB.getPersist().setAutoCommit(false);

		// INSERT HEADER
		AppGroup appGrp = (AppGroup) mp.get(ConstClientServer.STR_HDR);
		if (appGrp.getId().equalsIgnoreCase("administrator")) {
			// return 1;
		}
		setModifiedDate(appGrp);
		int n = AyukuDB.getPersist().update(appGrp);

		// end

		// DELETE ALL DETAIL
		AyukuDB.getPersist().executeUpdate(
				"delete from app_user_group_func where trim(group_id) = ?",
				new Object[] { appGrp.getId() });
		// end

		// INSERT DETAIL
		int ndtl = 0;

		List<VGroupFunctions> lst = (List<VGroupFunctions>) mp
				.get(ConstClientServer.STR_DTL);

		for (int j = 0; j < lst.size(); j++) {
			VGroupFunctions fnc = (VGroupFunctions) lst.get(j);
			System.out.println("Id: " + fnc.getId());
			System.out.println("Name: " + fnc.getName());
			System.out.println("View: " + fnc.getView());
			System.out.println("Add: " + fnc.getAdd());
			System.out.println("Edit: " + fnc.getEdit());
			System.out.println("Delete: " + fnc.getDelete());

			AppUserGroupFunc groupfunc = new AppUserGroupFunc();
			groupfunc.setGroupId(appGrp.getId());
			groupfunc.setFuncId(fnc.getId());
			groupfunc.setAccessView(fnc.getView());
			groupfunc.setAccessAdd(fnc.getAdd());
			groupfunc.setAccessEdit(fnc.getEdit());
			groupfunc.setAccessDelete(fnc.getDelete());

			// setModifiedDAte
			setDtlDateuser(groupfunc, appGrp);
			// end of

			ndtl += AyukuDB.getPersist().insert(groupfunc);
		}

		AyukuDB.getPersist().commit();
		AyukuDB.getPersist().setAutoCommit(true);
		return n;
	}

	private static void setModifiedDate(AppGroup pjo) throws Exception {
		pjo.setModifiedDate(UtilServer.getCurrentDate());
		if (pjo.getCreatedDate() == null) {
			pjo.setCreatedDate(UtilServer.getCurrentDate());
		}
	}

	private static void setDtlDateuser(AppUserGroupFunc groupfunc,
			AppGroup appGrp) {
		// modified
		groupfunc.setModifiedBy(appGrp.getModifiedBy());
		groupfunc.setModifiedDate(appGrp.getModifiedDate());
		groupfunc.setCreatedBy(appGrp.getCreatedBy());
		groupfunc.setCreatedDate(appGrp.getCreatedDate());
		// end
	}
}
